package com.zysd.collection.scheduler.service.model.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lensyn.common.exception.entity.MsgException;
import com.lensyn.common.utils.domain.common.PageResponse;
import com.zysd.collection.scheduler.entity.SchedulerTaskModel;
import com.zysd.collection.scheduler.service.model.SchedulerModelTaskService;
import com.zysd.collection.scheduler.service.model.SchedulerTaskModelService;
import com.zysd.collection.scheduler.system.constants.Constants;
import com.zysd.collection.scheduler.condition.TaskModelCondition;
import com.zysd.collection.scheduler.dao.SchedulerTaskModelDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务模板service 实现类
 *
 * @author liuht
 * @date 2017/10/13 9:32
 */
@Service
public class SchedulerTaskModelServiceImpl implements SchedulerTaskModelService {

    @Autowired
    private SchedulerTaskModelDao modelDao;

    @Autowired
    private SchedulerModelTaskService modelTaskService;

    @Override
    public SchedulerTaskModel getById(Long id) {
        return modelDao.selectByPrimaryKey(id);
    }

    @Override
    public PageResponse<SchedulerTaskModel> getListPage(TaskModelCondition condition) {
        PageHelper.offsetPage(condition.getOffset(), condition.getRows());
        List<SchedulerTaskModel> models = modelDao.selectByCondition(condition);
        for (SchedulerTaskModel model : models) {
            model.setTaskStatus(modelTaskService.modelTaskStatus(model).getCode());
        }
        Page<SchedulerTaskModel> page = (Page<SchedulerTaskModel>) models;
        return new PageResponse<>((int) page.getTotal(), models);
    }

    @Override
    public void addModel(SchedulerTaskModel model) {
        if (modelDao.insertSelective(model) != 1) {
            throw new MsgException("新增模板失败,条数不等于1");
        }
    }

    @Override
    public void disableModel(Long id) {
        SchedulerTaskModel model = modelDao.selectByPrimaryKey(id);
        model.setIsEnable(Constants.ISENABLE_NO);
        updateModelByid(model);
    }

    @Override
    public void enableModel(Long id) {
        SchedulerTaskModel model = modelDao.selectByPrimaryKey(id);
        model.setIsEnable(Constants.ISENABLE_YES);
        updateModelByid(model);
    }

    @Override
    public void updateModelByid(SchedulerTaskModel model) {
        if (modelDao.updateByPrimaryKeySelective(model) != 1) {
            throw new MsgException("更新模板失败,条数不等于1");
        }
    }
}
